<route lang="json5">
{
  layout: 'tabbar',
  style: {
    navigationStyle: 'custom',
    navigationBarTitleText: '单身夜话',
  },
}
</route>

<template>
  <view>
    <z-paging 
      ref="pagingRefs" 
      v-model="dataList" 
      :default-page-size="10"
      :safe-area-inset-bottom="true"
      :refresher-complete-delay="500"
      @query="queryList"
    >
      <template #top>
        <!-- 导航 -->
        <!--  #ifdef MP-WEIXIN -->
        <wd-navbar 
          placeholder 
          safeAreaInsetTop 
          title="单身夜话" 
        ></wd-navbar>
        <!--  #endif -->
          
        <!-- 搜索条件 -->
        <view class="w-750rpx m-a flex-sb-center pl-32rpx pr-32rpx py-15rpx box-border bg-linear-9 rounded-24rpx"
          style="box-shadow: 0 2rpx 4rpx 0 rgba(0,0,0,.25);"
        >
          <view class="flex-a-center">
            <wd-switch v-model="virtualCallFlag" size="32rpx" @change="handleChangeVirtualCallFlag" />
            <view class="inline-block font-size-28rpx color-#9C6DEF ml-10rpx">是否同意接听虚拟通话</view>
          </view>
          <!-- <view class="search-wrap w-555rpx h-64rpx flex-sb-center bg-white rounded-full box-border pl-66rpx pr-66rpx"
            :class="[{ 
              'dark-color2': themeConfig.theme === 'dark',
              '!w-355rpx': platform === 'mp-weixin'
            }]"
          >
            <view class="flex-center">
              <i class="iconfont icon-sousuo font-size-34rpx mr-10rpx color-#BBB"></i>
            </view>
            <view class="w-460rpx relative input-box"
              :class="[{
                '!w-260rpx': platform === 'mp-weixin'
              }]"
            >
              <wd-input 
                class="w-full !h-60rpx" 
                type="text" 
                v-model="pagination.code" 
                placeholder="搜索ID" 
                @confirm="handleSearchConfirm"
              />
            </view>
          </view> -->
          <view class="w-260rpx h-60rpx flex-center !flex-justify-end search-btn relative" @click="toFilter()">
            <view class="w-2px h-full position-l-center bg-#fff"></view>
            <i class="iconfont icon-shaixuan font-size-30rpx mr-4rpx color-#9C6DEF"></i>
            <wd-text text="筛选通话对象" color="#9C6DEF" size="28rpx"></wd-text>
          </view>
        </view>
        <!-- 走马灯 -->
        <view class="w-750rpx m-a" v-if="isShowTips">
          <wd-notice-bar 
            text="在了解对方之前，不要透露过多个人信息，包括地址、电话号码等敏感信息。任何要求提供验证码或借钱的行为都可能是骗局，务必保持警惕‌。严禁涉及色情、政治及各种不良敏感话题等。"
            :color="themeConfig.theme === 'dark' ? '#fff': '#1B1116'"
            background-color="rgba(255, 255, 255, 0)"
          >
            <template #prefix>
              <view class="w-32rpx h-32rpx font-size-0 pr-16rpx">
                <wd-img 
                  width="100%" 
                  height="100%" 
                  :src="tips" 
                  mode="aspectFill" 
                />
              </view>
            </template>
          </wd-notice-bar>
        </view>
        <view style="width: 100%;height: 36px;" v-else></view>
      </template>
      <template #bottom>
        <view class="w-full h-50px"></view>
      </template>
      
      <!-- 单身夜话列表 -->
      <view class="bg-#fff"
        :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
      >
        <!-- 骨架屏 - 加载中 -->
        <view v-if="isFirst">
          <view class="w-750rpx m-a bg-#fff"
            :class="[{ 'dark-color': themeConfig.theme === 'dark' }]"
            v-for="item in 3"
            :key="item"
          >
            <view class="w-center flex pt-24rpx pb-24rpx">
              <wd-skeleton animation="gradient" :row-col="[{ size: '124rpx', type: 'circle' }]" />
              <wd-skeleton 
                animation="gradient" 
                :custom-style="{ width: '100%', marginLeft: '12px' }" 
                :row-col="[{ width: '30%' }, { width: '60%' }, { width: '50%' }]" 
              />
            </view>
            <view class="border-1px"></view>
          </view>
        </view>

        <!-- 加载中 -->
        <view class="flex-center py-50rpx" v-if="!isFirst && loading">
          <wd-loading size="32rpx" color="#9C6DEF" />
        </view>

        <talk-item
          v-for="item in dataList"
          :key="item.id"
          :data="item"
          @makeCall="getBindPhoneUserIdConfirm"
        />
      </view>
    </z-paging>
    
    <!-- 虚拟通话 -->
    <wd-action-sheet 
      custom-class="vip-bg-color"
      v-model="showPhoneTips" 
      :actions="enumParams.phoneVipActions" 
      cancel-text="取消"
      title=""
      @select="selectPhone"
    />
  </view>
</template>

<script lang="ts" setup>
import TalkItem from "@/components/list-item/talk-item.vue";
import { useCommonStore, useThemeStore, useUserStore } from '@/store';
import { AddVirtualCall, GetBindPhoneUserId, GetUserPage, QueryByUserId } from "@/service/db_user";
import PLATFORM from '@/utils/platform'
import { useMessage, useToast } from "wot-design-uni";
import { tips } from "@/static/base64";
import { enumParams, share } from "@/enum";

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync();
// 主题颜色
const { themeConfig } = useThemeStore();
const common = useCommonStore();
const user = useUserStore();
const toast = useToast();
const message = useMessage();

// 搜索框值
const handleSearchConfirm = () => {
  pagingRefs.value.reload();
}

const platform = computed(() => {
  return PLATFORM.platform
})

const virtualCallFlag = ref(true);
// 用户接收虚拟通话配置
const handleChangeVirtualCallFlag = async () => {
  const res = await AddVirtualCall({
    userId: user.userInfo.id,
    virtualCallFlag: virtualCallFlag.value
  })
  pagingRefs.value.reload();
}

// 通过用户id获取用户接收虚拟通话配置表详情
const queryByUserId = async() => {
  const res = await QueryByUserId({
    userId: user.userInfo.id
  })
  virtualCallFlag.value = res.data.virtualCallFlag;
}

/**
 * 请求payload参数
 */
const pagination = reactive<AnyObj>({
  code: '',
  searchType: 'eveningTalk'
});
const dataList = ref([]);
const pagingRefs = ref();
const isFirst = ref(true);
const loading = ref(false);
const queryList = async (pageNo, pageSize) => {
  try {
    loading.value = true;
    const { data } = await GetUserPage(pagination, {
      pageNum: pageNo,
      pageSize,
    });
    isFirst.value = false;
    loading.value = false;
    const list = data.records || [];
    pagingRefs.value.complete(list);
  } catch (error) {
    loading.value = false;
    pagingRefs.value.complete(false);
    isFirst.value = false;
  }
}

// 去选择地区页面
const toFilter = () => {
  uni.navigateTo({
    url: '/feature/filter?type=talk&data=' + JSON.stringify(pagination)
  })
}

// 更新筛选条件
function handleUpdateFilter(data) {
  const _data = JSON.parse(data);
  const { filterData } = _data || {};
  
  for (const key in pagination) {
    if (['code', 'searchType'].includes(key)) continue;
    // if (['heights', 'ages', 'weights'].includes(key)) {
    //   pagination[key] = undefined;
    //   continue;
    // }
    pagination[key] = undefined;
  }
  Object.assign(pagination, filterData);

  pagingRefs.value.reload();
}

// 筛选条件确认
const handleFilterSubmit = (data = {}) => {
  Object.assign(pagination, data);
  pagingRefs.value.reload();
}

const handleClear = () => {
  for (const key in pagination) {
    delete pagination[key];
  }
  pagingRefs.value.reload();
}

const showPhoneTips = ref(false);
const selectedData = ref<any>({});
// 选择虚拟的通话
const selectPhone = (options) => {
  const { item } = options || {};
  if (item.type === 'vip') {
    uni.navigateTo({ url: '/feature/vip' });
  } else {
    // phoneConfirm(selectedData.value);
    getBindPhoneUserId(selectedData.value);
  }
}

// 是否vip
const isVip = () => {
  const { matchmakerFlag, membershipFlag, partnerFlag } = user.userInfo || {};
  return matchmakerFlag || membershipFlag || partnerFlag;
}

// 获取虚拟电话
const getBindPhoneUserIdConfirm = async (data) => {
  return toast.show('测试中');
  if (!user.isLogined) {
    uni.navigateTo({ url: '/pages/login/index' });
    return
  }
  if (!user.activityInfo.id) {
    toast.show('请先填写资料');
    setTimeout(() => {
      uni.navigateTo({ url: '/activity/addActivityInfo' })
    }, 1000)
    return
  }
  if (!isVip()) {
    selectedData.value = data;
    showPhoneTips.value = true;
    return;
  }
  phoneConfirm(data);
}

// 虚拟通话弹窗提示
const phoneConfirm = (data) => {
  message
    .confirm({
      msg: '虚拟通话每分钟0.12个乐缘币，\n充值更优惠',
      title: '通话收费提示'
    })
    .then(() => {
      getBindPhoneUserId(data);
    })
    .catch(() => {
      console.log('点击了取消按钮')
    })
}

const getBindPhoneUserId = async (data) => {
  try {
    const res = await GetBindPhoneUserId({
      userIdA: user.userInfo.id,
      userIdB: data.id
    })
    if (res.code == '6000012') {
      // common.paymentMsgConfirm({
      //   userId: user.userInfo.id,
      //   amount: 1,
      // }, () => {
      //   makeCall(res.data);
      // }, true, message)
      return 
    }
    makeCall(res.data);
  } catch (error) {
    console.log(error)
  }
}

// 拨打电话
const makeCall = (phoneNumber = '') => {
  uni.makePhoneCall({
    phoneNumber,
    success: (success) => {
      console.log(success)
    }
  })
}

// 如果自动筛选当前相反性别
const genderAutoFilter = () => {
  const userProfileInfoVo: any = user.userInfo.userProfileInfoVo || {};
  if (userProfileInfoVo.gender) {
    const gender = userProfileInfoVo.gender == '0' ? '1' : '0';
    pagination.gender = gender;
  }
}

const isShowTips = ref(false);
let count = 0;
onShow(() => {
  user.userInfo.id && queryByUserId();
  isShowTips.value = true;
  
  if (user.loginSubmit) {
    genderAutoFilter();
    setTimeout(() => {
      count++;
      count <= 1 && pagingRefs.value.reload();
    }, 100)
  }
})

onHide(() => {
  isShowTips.value = false;
})

onLoad(() => {
  uni.$on('talkUpdateFilter', handleUpdateFilter);
  genderAutoFilter();
  // toFilter();
})

// 页面卸载时移除监听
onUnload(() => {
  uni.$on('talkUpdateFilter', handleUpdateFilter);
})

onShareAppMessage(() => {
  const id = user.userInfo.id || '';
  return {
    title: '我满心期待，与你相遇的未来！',
    path: `/pages/tabbar/index?instrId=${id}`,
    imageUrl: share
  }
})
</script>

<style lang="scss" scoped>
// 搜索框 start
.search-wrap {
  box-shadow: 0 4rpx 18rpx 0 rgba(0, 0, 0, 0.04);
}
:deep(.wd-input__inner),
:deep(.wd-input__value),
:deep(.wd-input__body) {
  height: 60rpx !important;
}
:deep(.wd-input::after) {
  background: none !important;
}
// 搜索框 end

.search-box {
  justify-content: flex-start !important;

  .search-wrap {
    width: 360rpx !important;
  }
}

:deep(.wd-notice-bar) {
  padding-right: 0 !important;
}

:deep(.wd-action-sheet) {
  margin: 0 !important;
}

:deep(.wd-action-sheet__action) {
  padding-left: 4rpx;
  padding-right: 4rpx;
  height: auto !important;

  .wd-action-sheet__name {
    line-height: 48rpx;
    white-space: pre-wrap;
  }
}

</style>
    